import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css'; // progress bar style
import { storage } from '@/utils';
import { useMenus } from '@/store/useMenus';
import dynamicRouters from './dynamic-routers';

NProgress.configure({ showSpinner: false });

let notFoundCounter = 0;

export default function (router) {
  router.beforeEach((to, from, next) => {
    NProgress.start();
    // 设置html title
    if (to.meta.title) {
      document.title = to.meta.title;
    }
    // 跳转登录页
    if (!storage.get('tsp-access_token') && to.path != '/login') {
      return next('/login');
    }
    // 跳转登录页时清空localstorage
    if (to.path == '/login') {
      storage.clear();
    }

    const menuStore = useMenus();
    // 刷新时动态路由处理
    if (to.name == 'NotFound') {
      dynamicRouters(ref(menuStore.menus));
      notFoundCounter++;
      const t = setTimeout(() => {
        if (notFoundCounter > 1) {
          next();
        } else {
          router.push(to.fullPath);
        }
        clearTimeout(t);
      }, 500);
      return;
    }
    // tag标签
    const notTags = ['/login'];
    if (!menuStore.tags.find((m) => m.fullPath == to.fullPath) && !notTags.includes(to.path)) {
      menuStore.tags.push(to);
    }
    notFoundCounter = 0;
    next();
  });

  router.afterEach(() => {
    NProgress.done();
  });
}
